package com.example.tangyee.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.adapter.MyRecyclerViewAdapter;
import com.example.tangyee.bean.Article;
import com.example.tangyee.utils.GetArticlesForType;
import com.example.tangyee.utils.GlideApp;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class KnowledgeMenuActivity extends AppCompatActivity {

    private static final String TAG = "KnowledgeMenuActivity";

    private static final String PARAM1 = "mSupId";
    private static final String PARAM2 = "subId";

    private Unbinder mUnbinder;

    @BindView(R.id.back)
    View back;

    @BindView(R.id.knowledge_menu_recycler_view)
    RecyclerView mRecyclerView;

    private int page = 1;
    private List<Article> data = new ArrayList<>();
    private MyRecyclerViewAdapter<Article> mAdapter;
    private View footView;
    private LinearLayoutManager layoutManager;
    private GetArticlesForType.OnPostExecute execute;

    // 防止总在加载
    private boolean isLoading = false;

    private int mSupId = 0;
    private int mSubId = 0;

    public static Intent getKnowledgeMenuActivityIntent(Context context, int supId, int subId) {
        Intent intent = new Intent(context, KnowledgeMenuActivity.class);
        intent.putExtra(PARAM1, supId);
        intent.putExtra(PARAM2, subId);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_knowledge_menu);
        mUnbinder = ButterKnife.bind(this);

        mSupId = getIntent().getIntExtra(PARAM1, 0);
        mSubId = getIntent().getIntExtra(PARAM2, 0);

        // 初始化recyclerview
        initRecyclerView();
    }

    /*初始化RecyclerView*/
    private void initRecyclerView() {
        mAdapter = new MyRecyclerViewAdapter<>(data, this, R.layout.article_item_list_layout);
        footView = LayoutInflater.from(this).inflate(R.layout.item_foot_layout,null);
        mAdapter.addFooterView(footView);
        mAdapter.setItemViewHelper(new MyRecyclerViewAdapter.ItemViewHelper<Article>() {

            @Override
            public void onClick(View view, Article article) {
                Intent intent = new Intent(KnowledgeMenuActivity.this, KnowledgeDetailActicity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("knowID", article.getKnowID());
                bundle.putString("topTitle", article.getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onBindViewHolder(MyRecyclerViewAdapter.MyHolder holder, int position, Article article) {
                TextView title = holder.itemView.findViewById(R.id.title);
                title.setText(article.getTitle());
                TextView releaseDate = holder.itemView.findViewById(R.id.release_date);
                releaseDate.setText( article.getAuthor() + "    " + article.getReleaseDate() + "    " + article.getCount() + "访问");
                TextView summary = holder.itemView.findViewById(R.id.summary);
                summary.setText(article.getSummary());

                ImageView image = holder.itemView.findViewById(R.id.image);
                GlideApp.with(KnowledgeMenuActivity.this)
                        .load(article.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(image);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);

        execute = articles -> {
            if (articles == null) {
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("请求超时···");
            } else if (articles.size() == 0) {
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("没有数据了···");
            } else {
                ++ page;

                int count = mAdapter.getItemCount();
                mAdapter.updateDate(articles, false);

                if (count <= 1) {
                    ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                            Animation.RELATIVE_TO_SELF, 0f,
                            Animation.RELATIVE_TO_SELF, 0f);
                    sa.setDuration(1000);

                    AlphaAnimation aa = new AlphaAnimation(0, 1);
                    aa.setDuration(1000);

                    AnimationSet as = new AnimationSet(true);
                    as.setDuration(1000);
                    as.addAnimation(sa);
                    as.addAnimation(aa);

                    mRecyclerView.startAnimation(as);
                }
            }
            isLoading = false;
        };
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == mAdapter.getItemCount() && !isLoading) { // footItem 可见时，说明该加载更多了。
                    Log.d("test", "loading executed");
                    isLoading = true;
                    new GetArticlesForType(page, 10, mSupId, mSubId, execute).execute();
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                /*glide优化，提升性能?*/
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    GlideApp.with(KnowledgeMenuActivity.this).resumeRequests();
                }else {
                    GlideApp.with(KnowledgeMenuActivity.this).pauseRequests();
                }
            }
        });
    }

    @OnClick(R.id.back)
    public void back() {
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
